package com.example.piece.ui.activity

import android.os.Bundle
import com.therouter.router.Route
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.example.base.ext.getViewModel
import com.example.base.ext.toast
import com.example.base.ui.activity.BaseActivity
import com.example.base.ui.view.recyclerview.SpaceItemDecoration
import com.example.base.vm.onError
import com.example.piece.R
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ActivityHomeSearchBinding
import com.example.piece.ui.adapter.HomeFollowAdapter
import com.example.piece.ui.adapter.HomeSearchHotAdapter
import com.example.piece.vm.HelperViewModel
import com.example.piece.vm.HomeViewModel
import com.example.piece.vm.JokesViewModel
import com.kongzue.dialogx.dialogs.TipDialog

/**
 * 首页搜索
 */

@Route(path = RoutePath.MAIN_HOME_SEARCH)
class HomeSearchActivity : BaseActivity<ActivityHomeSearchBinding>() {
    private val helperViewModel: HelperViewModel by lazy {
        getViewModel<HelperViewModel>()
    }
    private val homeViewModel: HomeViewModel by lazy {
        getViewModel<HomeViewModel>()
    }

    //当前页数
    var page = 1

    /**  热门 Adapter  **/
    private val homeSearchHotAdapter: HomeSearchHotAdapter by lazy {
        val adapter = HomeSearchHotAdapter(emptyList())
        mBinding.rvHot.adapter = adapter
        mBinding.rvHot.addItemDecoration(SpaceItemDecoration(10))
        adapter
    }

    override fun getContentRes(): Int = R.layout.activity_home_search

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        homeSearchHotAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            jokesSearch(homeSearchHotAdapter.getItem(position), page.toString())
        })
        helperHotSearch()
    }

    /**
     * 2
     * 获取热搜关键词
     */
    private fun helperHotSearch() {
        helperViewModel.helperHotSearch(this) {
            if (it.code == 200) {
                homeSearchHotAdapter.setNewInstance(it.data.toMutableList())
            } else {
                TipDialog.show(it.msg)
            }
        } onError {
            TipDialog.show(it)

        }
    }

    /**
     * 3
     * 搜索段子
     * @param keyword 搜索的关键字
     * @param page 页数
     */
    private fun jokesSearch(keyword: String, page: String) {
        homeViewModel.jokesSearch(this, keyword, page) {
            this.page = this.page.inc()
        } onError {

        }
    }


}